<template>
  <div class="youbi-management">
    <h2>{{ $t('message.youbiManagement') }}</h2>
    
    <div class="youbi-filters">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input 
            v-model="filter.userId" 
            :placeholder="$t('message.userId')" 
            clearable
          />
        </el-col>
        <el-col :span="6">
          <el-select 
            v-model="filter.operationType" 
            :placeholder="$t('message.operationType')" 
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="type in operationTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="filter.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="loadYoubiRecords">{{ $t('message.search') }}</el-button>
          <el-button @click="resetFilters">{{ $t('message.reset') }}</el-button>
        </el-col>
      </el-row>
    </div>
    
    <div class="youbi-actions">
      <el-button type="primary" @click="openAdjustYoubiDialog">{{ $t('message.adjustYoubi') }}</el-button>
    </div>
    
    <el-table
      :data="youbiRecords"
      style="width: 100%"
      :default-sort="{ prop: 'createdAt', order: 'descending' }"
    >
      <el-table-column prop="userId" :label="$t('message.userId')" width="150" align="left" header-align="left" />
      <el-table-column prop="amount" :label="$t('message.amount')" width="120" align="left" header-align="left">
        <template #default="scope">
          <span :class="scope.row.amount >= 0 ? 'amount-increase' : 'amount-decrease'">
            {{ scope.row.amount >= 0 ? '+' : '' }}{{ scope.row.amount }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="balanceAfter" :label="$t('message.balanceAfter')" width="120" align="left" header-align="left" />
      <el-table-column prop="operationType" :label="$t('message.operationType')" width="120" align="left" header-align="left">
        <template #default="scope">
          {{ getOperationTypeLabel(scope.row.operationType) }}
        </template>
      </el-table-column>
      <el-table-column prop="operationDesc" :label="$t('message.description')" show-overflow-tooltip align="left" header-align="left" />
      <el-table-column prop="relatedId" :label="$t('message.relatedId')" width="150" show-overflow-tooltip align="left" header-align="left" />
      <el-table-column prop="createdAt" :label="$t('message.createdAt')" width="180" align="left" header-align="left">
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      style="margin-top: 20px; text-align: right;"
    />
    
    <!-- 优币调整对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="youbiForm" :rules="youbiRules" ref="youbiFormRef" label-width="120px">
        <el-form-item :label="$t('message.userId')" prop="userId">
          <el-input 
            v-model="youbiForm.userId" 
            :placeholder="$t('message.pleaseEnterUserId')"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.amount')" prop="amount">
          <el-input-number 
            v-model="youbiForm.amount" 
            :min="-100000" 
            :max="100000"
            :precision="2"
            :step="1"
            :placeholder="$t('message.pleaseEnterAmount')"
            style="width: 100%"
          ></el-input-number>
          <div class="amount-hint">
            {{ $t('message.amountHint') }}
          </div>
        </el-form-item>
        <el-form-item :label="$t('message.description')" prop="operationDesc">
          <el-input 
            v-model="youbiForm.operationDesc" 
            type="textarea"
            :rows="3"
            :placeholder="$t('message.pleaseEnterDescription')"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ $t('message.cancel') }}</el-button>
          <el-button type="primary" @click="adjustYoubi">{{ $t('message.confirm') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/stores/auth';

export default {
  name: 'YoubiManagement',
  setup() {
    const { t } = useI18n();
    const authStore = useAuthStore();
    
    // 优币记录数据
    const youbiRecords = ref([]);
    
    // 筛选条件
    const filter = reactive({
      userId: '',
      operationType: '',
      dateRange: []
    });
    
    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    });
    
    // 对话框相关
    const dialogVisible = ref(false);
    const dialogTitle = ref('');
    
    // 优币调整表单数据
    const youbiForm = reactive({
      userId: '',
      amount: 0,
      operationDesc: ''
    });
    
    const youbiFormRef = ref();
    
    // 选项数据
    const operationTypes = ref([
      { value: 'INCOME', label: t('message.income') },
      { value: 'EXPENSE', label: t('message.expense') },
      { value: 'TRANSFER', label: t('message.transfer') },
      { value: 'ADJUSTMENT', label: t('message.adjustment') }
    ]);
    
    // 表单验证规则
    const youbiRules = {
      userId: [
        { required: true, message: t('message.pleaseEnterUserId'), trigger: 'blur' }
      ],
      amount: [
        { required: true, message: t('message.pleaseEnterAmount'), trigger: 'blur' },
        { type: 'number', message: t('message.amountMustBeNumber'), trigger: 'blur' }
      ],
      operationDesc: [
        { required: true, message: t('message.pleaseEnterDescription'), trigger: 'blur' }
      ]
    };
    
    // 获取优币记录列表
    const loadYoubiRecords = async () => {
      try {
        // 构建查询参数
        const params = new URLSearchParams();
        params.append('page', pagination.currentPage);
        params.append('size', pagination.pageSize);
        
        if (filter.userId) params.append('userId', filter.userId);
        if (filter.operationType) params.append('operationType', filter.operationType);
        if (filter.dateRange && filter.dateRange.length === 2) {
          params.append('startDate', filter.dateRange[0]);
          params.append('endDate', filter.dateRange[1]);
        }
        
        const response = await fetch(`/api/admin/youbi/records?${params.toString()}`, {
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          const data = await response.json();
          youbiRecords.value = data.items || data;
          pagination.total = data.total || youbiRecords.value.length;
        } else {
          ElMessage.error(t('message.failedToLoadYoubiRecords'));
        }
      } catch (error) {
        console.error('Error loading youbi records:', error);
        ElMessage.error(t('message.failedToLoadYoubiRecords'));
      }
    };
    
    // 重置筛选条件
    const resetFilters = () => {
      filter.userId = '';
      filter.operationType = '';
      filter.dateRange = [];
      pagination.currentPage = 1;
      loadYoubiRecords();
    };
    
    // 打开优币调整对话框
    const openAdjustYoubiDialog = () => {
      dialogTitle.value = t('message.adjustYoubi');
      resetForm();
      dialogVisible.value = true;
    };
    
    // 重置表单
    const resetForm = () => {
      Object.assign(youbiForm, {
        userId: '',
        amount: 0,
        operationDesc: ''
      });
    };
    
    // 优币调整
    const adjustYoubi = async () => {
      try {
        await youbiFormRef.value.validate();
        
        // 确认调整
        await ElMessageBox.confirm(
          `${t('message.adjustYoubiConfirm')} ${youbiForm.userId} ${youbiForm.amount > 0 ? t('message.increase') : t('message.decrease')} ${Math.abs(youbiForm.amount)} ${t('message.youbi')}`,
          t('message.warning'),
          {
            confirmButtonText: t('message.confirm'),
            cancelButtonText: t('message.cancel'),
            type: 'warning'
          }
        );
        
        const response = await fetch('/api/admin/youbi/adjust', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            userId: youbiForm.userId,
            amount: youbiForm.amount,
            description: youbiForm.operationDesc
          })
        });
        
        if (response.ok) {
          ElMessage.success(t('message.adjustYoubiSuccess'));
          dialogVisible.value = false;
          loadYoubiRecords(); // 重新加载记录
        } else {
          const errorData = await response.json();
          ElMessage.error(errorData.message || t('message.adjustYoubiFailed'));
        }
      } catch (error) {
        if (error !== 'cancel' && error !== 'close') {
          console.error('Error adjusting youbi:', error);
          ElMessage.error(t('message.adjustYoubiFailed'));
        }
      }
    };
    
    // 获取操作类型标签
    const getOperationTypeLabel = (operationType) => {
      const type = operationTypes.value.find(t => t.value === operationType);
      return type ? type.label : operationType;
    };
    
    // 格式化日期
    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString();
    };
    
    // 分页处理
    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      pagination.currentPage = 1;
      loadYoubiRecords();
    };
    
    const handleCurrentChange = (page) => {
      pagination.currentPage = page;
      loadYoubiRecords();
    };
    
    onMounted(() => {
      loadYoubiRecords();
    });
    
    return {
      youbiRecords,
      filter,
      pagination,
      dialogVisible,
      dialogTitle,
      youbiForm,
      youbiFormRef,
      youbiRules,
      operationTypes,
      openAdjustYoubiDialog,
      adjustYoubi,
      resetFilters,
      loadYoubiRecords,
      getOperationTypeLabel,
      formatDate,
      handleSizeChange,
      handleCurrentChange
    };
  }
};
</script>

<style scoped>
.youbi-management {
  padding: 20px;
}

.youbi-filters {
  margin-bottom: 20px;
}

.youbi-actions {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}

.amount-increase {
  color: green;
  font-weight: bold;
}

.amount-decrease {
  color: red;
  font-weight: bold;
}

.amount-hint {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>